// 产品管理API服务（使用真实数据库）
const express = require('express');
const router = express.Router();
const Product = require('../models/Product');

// 获取所有产品
router.get('/products', async (req, res) => {
    try {
        const {
            page = 1,
            limit = 10,
            search = '',
            status = '',
            market = '',
            category_id = '',
            sortBy = 'created_at',
            sortOrder = 'DESC'
        } = req.query;
        
        const result = await Product.findAll({
            page: parseInt(page),
            limit: parseInt(limit),
            search,
            status,
            market,
            category_id,
            sortBy,
            sortOrder
        });
        
        res.json({
            success: true,
            data: result.data,
            pagination: result.pagination
        });
    } catch (error) {
        console.error('获取产品列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取产品列表失败'
        });
    }
});

// 获取单个产品
router.get('/products/:id', async (req, res) => {
    try {
        const product = await Product.findById(parseInt(req.params.id));
        
        if (!product) {
            return res.status(404).json({
                success: false,
                message: '产品不存在'
            });
        }
        
        res.json({
            success: true,
            data: product
        });
    } catch (error) {
        console.error('获取产品失败:', error);
        res.status(500).json({
            success: false,
            message: '获取产品失败'
        });
    }
});

// 创建新产品
router.post('/products', async (req, res) => {
    try {
        const {
            sku, model, name_en, name_de, name_fr, name_es,
            description_en, description_de, description_fr, description_es,
            frame_material, frame_size, max_weight, wheel_size, hs_code, origin,
            certifications, price_usd, price_eur, price_gbp, stock_domestic,
            stock_overseas, safety_stock, weight, package_size, shipping_methods,
            banned_countries, wholesale_tiers, market_settings, technical_docs,
            accessories, status = 'active'
        } = req.body;
        
        // 验证必填字段
        if (!sku || !model || !name_en || !price_usd) {
            return res.status(400).json({
                success: false,
                message: 'SKU、型号、产品名称和价格是必填项'
            });
        }
        
        // 检查SKU是否重复
        const existingProduct = await Product.findBySku(sku);
        if (existingProduct) {
            return res.status(400).json({
                success: false,
                message: 'SKU已存在'
            });
        }
        
        const productData = {
            sku: sku.trim(),
            model: model.trim(),
            name_en: name_en.trim(),
            name_de: name_de || '',
            name_fr: name_fr || '',
            name_es: name_es || '',
            description_en: description_en || '',
            description_de: description_de || '',
            description_fr: description_fr || '',
            description_es: description_es || '',
            frame_material: frame_material || '',
            frame_size: frame_size || '',
            max_weight: parseInt(max_weight) || 0,
            wheel_size: wheel_size || '',
            hs_code: hs_code || '',
            origin: origin || '',
            certifications: certifications || [],
            price_usd: parseFloat(price_usd),
            price_eur: parseFloat(price_eur) || parseFloat(price_usd) * 0.92,
            price_gbp: parseFloat(price_gbp) || parseFloat(price_usd) * 0.79,
            stock_domestic: parseInt(stock_domestic) || 0,
            stock_overseas: parseInt(stock_overseas) || 0,
            safety_stock: parseInt(safety_stock) || 10,
            weight: parseFloat(weight) || 0,
            package_size: package_size || '',
            shipping_methods: shipping_methods || [],
            banned_countries: banned_countries || [],
            wholesale_tiers: wholesale_tiers || [],
            market_settings: market_settings || {},
            technical_docs: technical_docs || {},
            accessories: accessories || [],
            status: status
        };
        
        const newProduct = await Product.create(productData);
        
        res.status(201).json({
            success: true,
            message: '产品创建成功',
            data: newProduct
        });
    } catch (error) {
        console.error('创建产品失败:', error);
        res.status(500).json({
            success: false,
            message: '创建产品失败'
        });
    }
});

// 更新产品
router.put('/products/:id', async (req, res) => {
    try {
        const productId = parseInt(req.params.id);
        const existingProduct = await Product.findById(productId);
        
        if (!existingProduct) {
            return res.status(404).json({
                success: false,
                message: '产品不存在'
            });
        }
        
        // 如果更新SKU，检查是否重复
        if (req.body.sku && req.body.sku !== existingProduct.sku) {
            const productWithSku = await Product.findBySku(req.body.sku);
            if (productWithSku && productWithSku.id !== productId) {
                return res.status(400).json({
                    success: false,
                    message: 'SKU已存在'
                });
            }
        }
        
        // 处理数值类型字段
        const updateData = { ...req.body };
        
        if (updateData.price_usd) updateData.price_usd = parseFloat(updateData.price_usd);
        if (updateData.price_eur) updateData.price_eur = parseFloat(updateData.price_eur);
        if (updateData.price_gbp) updateData.price_gbp = parseFloat(updateData.price_gbp);
        if (updateData.stock_domestic) updateData.stock_domestic = parseInt(updateData.stock_domestic);
        if (updateData.stock_overseas) updateData.stock_overseas = parseInt(updateData.stock_overseas);
        if (updateData.safety_stock) updateData.safety_stock = parseInt(updateData.safety_stock);
        if (updateData.max_weight) updateData.max_weight = parseInt(updateData.max_weight);
        if (updateData.weight) updateData.weight = parseFloat(updateData.weight);
        
        const updatedProduct = await Product.update(productId, updateData);
        
        res.json({
            success: true,
            message: '产品更新成功',
            data: updatedProduct
        });
    } catch (error) {
        console.error('更新产品失败:', error);
        res.status(500).json({
            success: false,
            message: '更新产品失败'
        });
    }
});

// 删除产品
router.delete('/products/:id', async (req, res) => {
    try {
        const productId = parseInt(req.params.id);
        const existingProduct = await Product.findById(productId);
        
        if (!existingProduct) {
            return res.status(404).json({
                success: false,
                message: '产品不存在'
            });
        }
        
        await Product.delete(productId);
        
        res.json({
            success: true,
            message: '产品删除成功'
        });
    } catch (error) {
        console.error('删除产品失败:', error);
        res.status(500).json({
            success: false,
            message: '删除产品失败'
        });
    }
});

// 批量操作
router.post('/products/batch', async (req, res) => {
    try {
        const { action, productIds, data } = req.body;
        
        if (!action || !productIds || !Array.isArray(productIds)) {
            return res.status(400).json({
                success: false,
                message: '操作类型和产品ID列表是必填项'
            });
        }
        
        let updatedProducts = [];
        let errors = [];
        
        switch (action) {
            case 'update_price':
                if (data.price_usd) {
                    const updateData = {
                        price_usd: parseFloat(data.price_usd),
                        price_eur: parseFloat(data.price_usd) * 0.92,
                        price_gbp: parseFloat(data.price_usd) * 0.79
                    };
                    updatedProducts = await Product.batchUpdate(productIds, updateData);
                }
                break;
                
            case 'update_stock':
                const updateData = {};
                if (data.stock_domestic !== undefined) updateData.stock_domestic = parseInt(data.stock_domestic);
                if (data.stock_overseas !== undefined) updateData.stock_overseas = parseInt(data.stock_overseas);
                if (Object.keys(updateData).length > 0) {
                    updatedProducts = await Product.batchUpdate(productIds, updateData);
                }
                break;
                
            case 'update_status':
                if (data.status) {
                    updatedProducts = await Product.batchUpdate(productIds, { status: data.status });
                }
                break;
                
            case 'update_market':
                if (data.market && data.active !== undefined) {
                    // 这里需要特殊处理JSON字段的更新
                    // 简化处理：直接更新整个market_settings字段
                    const updateData = { market_settings: data.market_settings };
                    updatedProducts = await Product.batchUpdate(productIds, updateData);
                }
                break;
                
            default:
                return res.status(400).json({
                    success: false,
                    message: '不支持的操作类型'
                });
        }
        
        res.json({
            success: true,
            message: `批量操作完成，成功更新 ${updatedProducts.length} 个产品`,
            data: updatedProducts,
            errors: errors.length > 0 ? errors : undefined
        });
    } catch (error) {
        console.error('批量操作失败:', error);
        res.status(500).json({
            success: false,
            message: '批量操作失败'
        });
    }
});

// 库存预警
router.get('/products/inventory/alerts', async (req, res) => {
    try {
        const alertProducts = await Product.getLowStockAlerts();
        
        res.json({
            success: true,
            data: alertProducts,
            total: alertProducts.length
        });
    } catch (error) {
        console.error('获取库存预警失败:', error);
        res.status(500).json({
            success: false,
            message: '获取库存预警失败'
        });
    }
});

// 产品统计
router.get('/products/analytics/summary', async (req, res) => {
    try {
        const analytics = await Product.getAnalytics();
        
        res.json({
            success: true,
            data: analytics
        });
    } catch (error) {
        console.error('获取产品统计失败:', error);
        res.status(500).json({
            success: false,
            message: '获取产品统计失败'
        });
    }
});

// 导出产品数据
router.get('/products/export', async (req, res) => {
    try {
        const { format = 'json' } = req.query;
        const result = await Product.findAll({ limit: 1000 }); // 导出最多1000条记录
        
        if (format === 'csv') {
            // 简化的CSV导出
            const headers = ['SKU', 'Model', 'Name (EN)', 'Price (USD)', 'Stock Domestic', 'Stock Overseas'];
            const csvData = result.data.map(product => [
                product.sku,
                product.model,
                product.name_en,
                product.price_usd,
                product.stock_domestic,
                product.stock_overseas
            ].join(','));
            
            const csvContent = [headers.join(','), ...csvData].join('\n');
            
            res.setHeader('Content-Type', 'text/csv');
            res.setHeader('Content-Disposition', `attachment; filename=products-${new Date().toISOString().split('T')[0]}.csv`);
            res.send(csvContent);
        } else {
            res.json({
                success: true,
                data: result.data,
                exported_at: new Date().toISOString()
            });
        }
    } catch (error) {
        console.error('导出产品数据失败:', error);
        res.status(500).json({
            success: false,
            message: '导出产品数据失败'
        });
    }
});

// 导入产品数据
router.post('/products/import', async (req, res) => {
    try {
        const { products: importedProducts, merge = false } = req.body;
        
        if (!Array.isArray(importedProducts)) {
            return res.status(400).json({
                success: false,
                message: '导入数据格式不正确'
            });
        }
        
        let importedCount = 0;
        let updatedCount = 0;
        let errors = [];
        
        for (const importedProduct of importedProducts) {
            try {
                if (!importedProduct.sku) {
                    errors.push(`SKU不能为空`);
                    continue;
                }
                
                const existingProduct = await Product.findBySku(importedProduct.sku);
                
                if (existingProduct) {
                    if (merge) {
                        await Product.update(existingProduct.id, importedProduct);
                        updatedCount++;
                    } else {
                        errors.push(`SKU ${importedProduct.sku} 已存在`);
                    }
                } else {
                    await Product.create(importedProduct);
                    importedCount++;
                }
            } catch (error) {
                errors.push(`导入产品 ${importedProduct.sku || '未知'} 失败: ${error.message}`);
            }
        }
        
        res.json({
            success: true,
            message: `导入完成: 新增 ${importedCount} 个产品，更新 ${updatedCount} 个产品`,
            errors: errors.length > 0 ? errors : undefined
        });
    } catch (error) {
        console.error('导入产品数据失败:', error);
        res.status(500).json({
            success: false,
            message: '导入产品数据失败'
        });
    }
});

// 搜索产品
router.get('/products/search', async (req, res) => {
    try {
        const { q, limit = 20, offset = 0 } = req.query;
        
        if (!q) {
            return res.status(400).json({
                success: false,
                message: '搜索关键词不能为空'
            });
        }
        
        const products = await Product.search(q, { limit: parseInt(limit), offset: parseInt(offset) });
        
        res.json({
            success: true,
            data: products,
            total: products.length
        });
    } catch (error) {
        console.error('搜索产品失败:', error);
        res.status(500).json({
            success: false,
            message: '搜索产品失败'
        });
    }
});

module.exports = router;